package middleware

import (
	"gin-chat-server/code"
	"gin-chat-server/common"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

func JwtMiddleware() gin.HandlerFunc {

	return func(c *gin.Context) {
		// 验证token是否存在
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.Set("already_sent", true)
			common.Fail(http.StatusUnauthorized, code.GetErrorMessage(code.ErrUnauthorized)).Send(c)
			c.Abort()
			return
		}
		// 验证token格式
		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || parts[0] != "Bearer" {
			c.Set("already_sent", true)
			common.Fail(http.StatusUnauthorized, code.GetErrorMessage(code.ErrUnauthorized)).Send(c)
			c.Abort()
			return
		}
		// 验证token
		claims, err := common.ParseToken(parts[1])
		if err != nil {
			common.Fail(http.StatusUnauthorized, code.GetErrorMessage(code.ErrUnauthorized)).Send(c)
			c.Abort()
			return
		}
		c.Set("currentUser", claims)
		c.Next()
	}
}
